package com.hhf.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.feiapicommon.model.entity.UserInterfaceInfo;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.constant.CommonConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.mapper.UserInterfaceInfoMapper;
import com.hhf.springboot.model.dto.userInterfaceInfo.UserInterfaceInfoQueryRequest;

import com.hhf.springboot.model.vo.UserInterfaceInfoVO;
import com.hhf.springboot.service.UserInterfaceInfoService;
import com.hhf.springboot.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86138
 * @description 针对表【user_interface_info(用户接口信息)】的数据库操作Service实现
 * @createDate 2024-10-06 18:37:55
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {


    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Integer leftCount = userInterfaceInfo.getLeftCount();
        Integer totalCount = userInterfaceInfo.getTotalCount();
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();


        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(leftCount < 0 || totalCount < 0, ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (userId < 0 || interfaceInfoId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口名称过长");
        }
    }

    @Override
    public QueryWrapper<UserInterfaceInfo> getQueryWrapper(UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest) {
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        if (userInterfaceInfoQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = userInterfaceInfoQueryRequest.getSortField();
        String sortOrder = userInterfaceInfoQueryRequest.getSortOrder();
        Long id = userInterfaceInfoQueryRequest.getId();
        Integer status = userInterfaceInfoQueryRequest.getStatus();
        Long userId = userInterfaceInfoQueryRequest.getUserId();
        Long interfaceInfoId = userInterfaceInfoQueryRequest.getInterfaceInfoId();
        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(interfaceInfoId), "interface_info_id", interfaceInfoId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<UserInterfaceInfoVO> getUserInterfaceInfoVOPage(Page<UserInterfaceInfo> userInterfaceInfoPage) {
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoPage.getRecords();
        Page<UserInterfaceInfoVO> userInterfaceInfoVOPage = new Page<>(userInterfaceInfoPage.getCurrent(), userInterfaceInfoPage.getSize(), userInterfaceInfoPage.getTotal());
        if (CollUtil.isEmpty(userInterfaceInfoList)) {
            return userInterfaceInfoVOPage;
        }
        // 填充信息
        List<UserInterfaceInfoVO> userInterfaceInfoVOList = userInterfaceInfoList
                .stream()
                .map(userInterfaceInfo -> objToVo(userInterfaceInfo))
                .collect(Collectors.toList());
        userInterfaceInfoVOPage.setRecords(userInterfaceInfoVOList);
        return userInterfaceInfoVOPage;
    }

    @Override
    public boolean invokeCount(Long userId, Long interfaceInfoId) {
        //1. 判断参数是否合理
        if (userId < 0 || interfaceInfoId < 0){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.查看是否存在
        UpdateWrapper<UserInterfaceInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("interface_info_id",interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(wrapper);
        if (userInterfaceInfo == null){
            throw  new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //3.totol_count + 1 and left_count - 1
        wrapper.setSql("total_count = total_count + 1,left_count = left_count - 1");
        boolean result = this.update(wrapper);
        //4.返回
        return result;
    }

    /**
     * 对象转包装类
     *
     * @param userInterfaceInfo
     * @return
     */
    public static UserInterfaceInfoVO objToVo(UserInterfaceInfo userInterfaceInfo) {
        if (userInterfaceInfo == null) {
            return null;
        }
        UserInterfaceInfoVO userInterfaceInfoVO = new UserInterfaceInfoVO();
        BeanUtils.copyProperties(userInterfaceInfo, userInterfaceInfoVO);
        return userInterfaceInfoVO;
    }

}




